#include "jtoolwidget.h"
#include "jtoolunitbox.h"

#include <QVBoxLayout>
#include <QToolBox>

namespace QTE
{

class Q_DECL_HIDDEN JToolWidgetPrivate
{
public:
	explicit JToolWidgetPrivate(JToolWidget *q_ptr);

public:
	QVBoxLayout *m_layout;
	QList<JToolUnitBox*> m_unitBoxList;
	bool m_chceckable = true;
};

JToolWidgetPrivate::JToolWidgetPrivate(JToolWidget *q_ptr) :
	m_layout(new QVBoxLayout())
{
	q_ptr->setLayout(m_layout);
	m_layout->setContentsMargins(0,0,0,0);

#if QT_VERSION < QT_VERSION_CHECK(6,0,0)
	m_layout->setMargin(0);
#endif //qt6
}

/*-----------------------------------------------------------------------------------------*/

JToolWidget::JToolWidget(QWidget *parent) :
	QFrame(parent),
	d_ptr(new JToolWidgetPrivate(this))
{
	setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
}

JToolWidget::~JToolWidget()
{
	delete d_ptr;
}

void JToolWidget::insertItem(int index, const QString &text, QWidget *widget, bool checked)
{
	auto box = new JToolUnitBox(text);
	box->setCheckable(d_ptr->m_chceckable);
	box->setChecked(checked);
	box->setWidget(widget);

	d_ptr->m_unitBoxList.insert(index, box);
	d_ptr->m_layout->insertWidget(index, box);
}

void JToolWidget::removeWidget(QWidget *widget)
{
	for(auto it=d_ptr->m_unitBoxList.begin(); it!=d_ptr->m_unitBoxList.end(); ++it)
	{
		if( *it != widget )
			continue;

		(*it)->deleteLater();
		d_ptr->m_unitBoxList.erase(it);

		d_ptr->m_layout->removeWidget(widget);
		break;
	}
}

void JToolWidget::removeItem(int index)
{
	Q_ASSERT(index >= 0 and index < d_ptr->m_unitBoxList.size());

	d_ptr->m_layout->removeWidget(d_ptr->m_unitBoxList[index]);
	d_ptr->m_unitBoxList[index]->deleteLater();
	d_ptr->m_unitBoxList.removeAt(index);
}

void JToolWidget::setCheckable(bool enable)
{
	d_ptr->m_chceckable = enable;
	for(auto &box : d_ptr->m_unitBoxList)
		box->setCheckable(enable);
}

int JToolWidget::count() const
{
	return d_ptr->m_unitBoxList.size();
}

} //namespace QTE
